package com.web.rss.gui;

import java.io.IOException;
import java.net.URL;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Set;
import java.util.Vector;

import javax.swing.JList;
import javax.swing.JScrollPane;
import javax.swing.ListSelectionModel;

import com.sun.syndication.feed.synd.SyndFeed;
import com.sun.syndication.io.FeedException;
import com.sun.syndication.io.SyndFeedInput;
import com.sun.syndication.io.XmlReader;

public class FeedListScrollPane extends JScrollPane {

	/**
	 * 
	 */
	private static final long serialVersionUID = -426568349396477758L;
	public HashMap<String, URL> feedList;
	public JList displayList;
	public SyndFeedInput input;
	Vector<String> namesList;
	
	public FeedListScrollPane(HashMap<String, URL> list) {
		feedList = list;
		namesList = new Vector<String>();
		Set<String> feedNames = feedList.keySet();
		Iterator<String> iter = feedNames.iterator();
		while (iter.hasNext()) {
			String tmp = iter.next();
			namesList.add(tmp);
			System.out.println("item : " + tmp);
		}
		displayList = new JList(namesList);
		displayList.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
		displayList.setSelectedIndex(0);
		
		displayList.setVisible(true);
		this.setViewportView(displayList);
	}
	
	public void updateFeedListDisplay() {
		
	}
	
	public SyndFeed getSelectedFeed() {
		SyndFeed localFeed = null;
		try {
			URL feedUrl = this.getSelectedFeedURL();
			localFeed = input.build(new XmlReader(feedUrl));
		}
		catch (IllegalArgumentException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (FeedException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return localFeed;
	}
	
	/**
	 * 
	 * @return L'URL du flux sélectionné dans la liste.
	 */
	public URL getSelectedFeedURL() {
		URL FeedURL = this.feedList.get(this.displayList.getSelectedValue());
		return FeedURL;
	}
}